﻿using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Musi.Core.CSV
{
    public static class CSVReader
    {
        public static CSVData[] CSVRead(string csv)
        {
            StringReader sr = new StringReader(csv);

            // Read first line
            string line = sr.ReadLine();
            List<CSVData> csvdatas = new List<CSVData>();
            CSVData readData;

            while(line != null)
            {
                readData = CSVReadLine(line);

                // The line with "" will not drop and will return instance of CSVData not null
                if(readData != null)
                {
                    csvdatas.Add(readData);
                }
                line = sr.ReadLine();
            }

            // If there are not any thing, it will return null
            if (csvdatas.Count <= 0)
                return null;
            else
                return csvdatas.ToArray();
        }

        /// <summary>
        /// Read and parse one csv line
        /// </summary>
        /// <remarks>
        /// Algorithm by @Zerous
        /// </remarks>
        public static CSVData CSVReadLine(string csvLine)
        {
            if (csvLine == null)
                return null;

            StringBuilder builder = new StringBuilder();
            CSVData csvData = new CSVData();
            bool inQuote = false;

            foreach (var ch in csvLine) {
                if (ch == '"') {
                    inQuote = !inQuote;
                } else if (ch == ',' && !inQuote) {
                    csvData.AddElement(builder.ToString());
                    builder.Clear();
                } else {
                    if (inQuote || !char.IsWhiteSpace(ch)) builder.Append(ch);
                }
            }

            if (builder.Length != 0) csvData.AddElement(builder.ToString());

            return csvData;
        }
    }
}
